import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yysk_app/model/collection_model/my_collection_list_by_collection_id_model.dart';
import 'package:yysk_app/model/market_model/market_batch_sale_my_list_model.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_exchange_psw.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_page.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';

class BulkSalesAndCancellationOfSalesController extends GetxController {
  var title = '批量出售'.obs;
  var type = '1'.obs; //0 批量取消出售 1批量出售
  var id = '0'.obs; //0 批量出售 1批量取消出售
  var num = '0'.obs; //
  int pageNum = 1;
  int pageSize = 10;
  var listSell = RxList<MyCollectionListByCollectionIdItem>([]);
  var listSellChoose = RxList<MyCollectionListByCollectionIdItem>([]);
  var listUnSell = RxList<MarketBatchSaleMyListModelItem>([]);
  var listUnSellChoose = RxList<MarketBatchSaleMyListModelItem>([]);
  //出售控制器
  final TextEditingController saleController = TextEditingController();
  final ScrollController scrollController = ScrollController();
  var count = 0.obs;
  var headUrl = '';
  var headName = '';
  var headPrice = '';

  var serviceCharge = '';
  Timer? timer;
  var maxlength = 20.obs; // 排除上链中的状态
  var isSelectAll = false.obs;
  @override
  void onInit() {
    super.onInit();
    type.value = Get.parameters['type'] ?? Get.arguments['type'];
    id.value = Get.parameters['id'] ?? Get.arguments['id'];
    headUrl = Get.arguments['headUrl'] ?? '';
    headName = Get.arguments['headName'] ?? '';
    headPrice = Get.arguments['headPrice'] ?? '';
    serviceCharge = Get.arguments['serviceCharge'] ?? '';
    if (type.value == '1') {
      title.value = '批量出售';
      getCollectionListByCollectionId();
    } else {
      title.value = '批量取消出售';
      getMySellList();
    }

    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        if (type.value == '1') {
          title.value = '批量出售';
          // getCollectionListByCollectionId(loadMore: true);
        } else {
          title.value = '批量取消出售';
          getMySellList(loadMore: true);
        }
      }
    });
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
    saleController.dispose();
  }

  Future<void> handleRefresh() async {
    if (type.value == '1') {
      getCollectionListByCollectionId();
      listSellChoose.value = [];
    } else {
      getMySellList();
         listUnSellChoose.value = [];
    }
  }

  //藏品列表 取消售卖列表
  getMySellList({loadMore = false}) {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    try {
      http.netFetch<MarketBatchSaleMyListModel>(
        ProductApi.mySaleOrders,
        params: {
          'pageNum': pageNum,
          'pageSize': 20,
          'collectionId': id.value,
          'saleType': 'INCUBATION',
        },
        method: Method.post,
        success: (result) {
          List<MarketBatchSaleMyListModelItem> items = result.data?.list ?? [];
          if (loadMore && items.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            listUnSell.clear();
          }
          listUnSell.addAll(items);
        var iterator = items.iterator;
          var num = 0; //计算最大勾选的时候用
          while (iterator.moveNext()) {
            var item = iterator.current;
            if(item.status!='FROZEN'){
              num++;
            }
          }
          maxlength.value = num;
        },
      );
    } catch (e) {
      if (loadMore) {
        pageNum--;
      }
    }
  }

  //藏品列表
  getCollectionListByCollectionId({loadMore = false}) {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    try {
      http.netFetch<MyCollectionListByCollectionIdModel>(
        ProductApi.collectionListByCollectionId,
        params: {
          'pageNum': pageNum,
          'pageSize': 1000,
          'collectionId': id.value,
          'isSale': true,
        },
        method: Method.post,
        success: (result) {
          List<MyCollectionListByCollectionIdItem> items =
              result.data?.list ?? [];
          if (loadMore && items.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            listSell.clear();
          }
          var iterator = items.iterator;
          var num = 0; //计算最大勾选的时候用
          while (iterator.moveNext()) {
            var item = iterator.current;
            if(item.chainStatus!='WAITING'){
              num++;
            }
          }
          maxlength.value = num;
          listSell.addAll(items);
        },
      );
    } catch (e) {
      if (loadMore) {
        pageNum--;
      }
    }
  }

  //出售的列表数据
  Future<void> chooseListSell(dynamic tokenId,bool select ) async {
    consoleLog('${listSellChoose.length}====${maxlength.value}');
     if(listSellChoose.length>=maxlength.value&&select==false){
         return;
      }
    for (var element in listSell) {
      if (element.tokenId == tokenId) {
        element.isSelect = !element.isSelect!;
      }
    }
    count++;
    listSellChoose.value = [];
    for (var element in listSell) {
      if (element.isSelect == true) {
        listSellChoose.add(element);
      }
    }
  }


  unSaleList({required List<String> dataList, required String password}) {
    http.netFetch<dynamic>(
      ProductApi.cancelSaleOrder,
      params: {'saleOrderIds': dataList, 'payPassword': password},
      method: Method.post,
      success: (result) {
        if (result.code == 200) {
          showToast('已取消出售');
          getMySellList();
        }
      },
    );
  }

  //是否开通交易密码
  Future<dynamic> isSetPayPassword() async {
    try {
      showConfirmDialog(
        context: Get.context!,
        message: '请先设置交易密码',
        messages: [],
        fontSize: 14,
        actions: [
          ActionModel(label: '取消', onPressed: () {}),
          ActionModel(
            label: '前往设置',
            onPressed: () {
              Get.toNamed(ChangeExchangePassword.path);
            },
          ),
        ],
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  selectAll() {
  
     if(listSellChoose.length!=maxlength.value){
         for (var element in listSell) {
      if(listSellChoose.length<maxlength.value&&element.chainStatus != 'WAITING'&&!listSellChoose.contains(element)){
          element.isSelect = true;
          listSellChoose.add(element);
      }
    }
     }else{
         for (var element in listSell) {
         element.isSelect = false;
         listSellChoose.value = [];
    }
     }
    count.value++;
  }
  selectAllUnSell(){

 if(listUnSellChoose.length!=maxlength.value){
         for (var element in listUnSell) {
      if(listUnSellChoose.length<maxlength.value&&element.status != 'FROZEN'&&!listUnSellChoose.contains(element)){
          element.isSelect = true;
          listUnSellChoose.add(element);
      }
    }
     }else{
         for (var element in listUnSell) {
         element.isSelect = false;
         listUnSellChoose.value = [];
    }
     }
    count.value++;
  }

    //取消出售的列表数据
  Future<void> chooseListUnSell(dynamic id,bool select) async {
       consoleLog('${listUnSellChoose.length}====${maxlength.value}22');
     if(listUnSellChoose.length>=maxlength.value&&select==false){
         return; 
      }
    for (var element in listUnSell) {
      if (element.id == id) {
        element.isSelect = !element.isSelect!;
      }
    }
    count++;
    listUnSellChoose.value = [];
    for (var element in listUnSell) {
      if (element.isSelect == true) {
        listUnSellChoose.add(element);
      }
    }
  }

}
